﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TiposComuns.Objectos;

namespace Servidor.Objectos.Pesquisa
{
    [Serializable]
    public class SortedArray
    {
        #region Attributes
        private Person[] array;
        private BigInteger[] keys;
        private int size;
        private int lenght = 0;
        #endregion

        #region Constructors
        public SortedArray()
        {
            array = new Person[1];
            keys = new BigInteger[1];
            size = 1;
            lenght = 0;
        }

        public SortedArray(int n)
        {
            array = new Person[n];
            keys = new BigInteger[n];
            size = n;
            lenght = 0;
        }
        #endregion

        #region Modifiers
        public Person[] Array
        {
            get { return array; }
            set { array = value; }
        }

        public BigInteger[] Keys
        {
            get { return keys; }
            set { keys = value; }
        }

        public int Size
        {
            get { return size; }
            set { size = value; }
        }

        public int Lenght
        {
            get { return lenght; }
            set { lenght = value; }
        }
        #endregion

        #region Methods
        public bool Add(BigInteger key, Person obj, out Person rems)
        {
            rems = null;

            if (obj == null) return false;
                        

            int i;
            for (i = 0; i < lenght ; i++)
            {
                if (key < keys[i])
                {
                    BigInteger temp = keys[i];
                    Person tp = array[i];
                    keys[i] = key;
                    array[i] = obj;
                    obj = tp;
                    key = temp;
                    break;
                }
                if (obj.Username.Equals(array[i].Username))
                    return false;
            }

            if (i == size) return false;

            i += (i == lenght) ? 0 : 1;
            lenght += (lenght < size) ? 1 : 0;
            
            while (i < lenght)
            {
                BigInteger temp = keys[i];
                Person tp = array[i];
                keys[i] = key;
                array[i] = obj;
                obj = tp;
                key = temp;
                i++;
            }

            rems = obj;

            return true;
        }

        public bool Contains(BigInteger dist,Person person)
        {
            for (int i = 0; i < lenght; i++)
            {
                if (person.Username.Equals(array[i].Username))
                    return true;
                if (dist < keys[i]) return false;
            }

            return false;
        }
        #endregion

    }
}
